<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of BScreenProcessQueue
 *
 * @author I062261
 */
class BScreenProcessQueue extends BUIScreen {

    public $processQueueFormModel = null;

    //put your code here
    public function render($data = null) {

        $this->processQueueFormModel = new MakeQueueFormModel('processQueue');
        //parent::render($data);
        $this->addRenderView('processQueue', 'processQueueView', array('screen' => $this));
        //$this->startRender();
    }

    protected function processNext($data = array()) {
        $transactionId = $data['transactionId'];
        $currentProcessQueue = 0;
        //find current process queue
        $mCurrentTranQueue = BMServiceQueueLineTransactionQueue::model()->findByAttributes(array('transaction_id' => $transactionId,
            'processqueue_status' => BAQQueueLine::processQueueStatus_Processing));

        if ($mCurrentTranQueue != NULL) {
            $currentProcessQueue = $mCurrentTranQueue->queue_number;
            $mCurrentTranQueue['processqueue_status'] = BAQQueueLine::processQueueStatus_Processed;
            $data2 = unserialize($mCurrentTranQueue['data']);
            $data2[BAQQueueLine::processQueueStatus_EndProcessTime] = time();
            $mCurrentTranQueue['data'] = serialize($data2);

            $mCurrentTranQueue->save();

            if (isset($data['queueMessage'])) {
                $mQueueMessage = new BMAOnlineQueueMessage();
                $mQueueMessage->queue_transaction_id = $mCurrentTranQueue->transaction_id;
                $mQueueMessage->queue_number = $mCurrentTranQueue->queue_number;
                $mQueueMessage->sender_id = Blyn::app()->getCurrentUser()->getId();
                $mQueueMessage->send_time = time();
                $mQueueMessage->data = $data['queueMessage'];
                $mQueueMessage->save();
            }
        }

        //find next process queue
        $mNextTranQueue = BMServiceQueueLineTransactionQueue::model()->findBySql(
                'select * from bln_app_onlinequeue_service_queueline_transaction_queue where
                    transaction_id = :TransactionId and processqueue_status = :ProcessStatus and queue_number > :CurrentQueueCount', array(':TransactionId' => $transactionId, ':CurrentQueueCount' => $currentProcessQueue,
            ':ProcessStatus' => BAQQueueLine::processQueueStatus_Pending));

        if ($mNextTranQueue != NULL) {
            $mNextTranQueue['processqueue_status'] = BAQQueueLine::processQueueStatus_Processing;
            $data2 = unserialize($mNextTranQueue['data']);
            $data2[BAQQueueLine::processQueueStatus_StartProcessTime] = time();
            $mNextTranQueue['data'] = serialize($data2);
            $mNextTranQueue->save();

            if (isset($data['queueMessage'])) {
                $mQueueMessage = new BMAOnlineQueueMessage();
                $mQueueMessage->queue_transaction_id = $mNextTranQueue->transaction_id;
                $mQueueMessage->queue_number = $mNextTranQueue->queue_number;
                $mQueueMessage->sender_id = Blyn::app()->getCurrentUser()->getId();
                $mQueueMessage->send_time = time();
                $mQueueMessage->data = $data['queueMessage'];
                $mQueueMessage->save();
            }
        }
    }

    protected function stopProcessQueue($data = array()) {
        $transactionId = $data['transactionId'];
        $currentProcessQueue = 0;
        //find current process queue
        $mCurrentTranQueue = BMServiceQueueLineTransactionQueue::model()->findByAttributes(array('transaction_id' => $transactionId,
            'processqueue_status' => BAQQueueLine::processQueueStatus_Processing));

        if ($mCurrentTranQueue != NULL) {
            $currentProcessQueue = $mCurrentTranQueue->queue_number;
            $mCurrentTranQueue['processqueue_status'] = BAQQueueLine::processQueueStatus_Processed;
            $data = unserialize($mCurrentTranQueue['data']);
            $data[BAQQueueLine::processQueueStatus_EndProcessTime] = time();
            $mCurrentTranQueue['data'] = serialize($data);

            $mCurrentTranQueue->save();
        }
    }

    public function checkProcessQueueStatus($transactionId, $userId = NULL) {

        $processQueueStatus = array();
        $currentProcessingQueue = 0;
        $averageProcessTime = -1;
        $totalProcessTime = 0;
        $count = 0;

        if ($this->isAjaxLinkClicked('processNextLink')) {
            //$this->processNext(array('transactionId' => $transactionId));
            if ($this->processQueueFormModel->processQueueMessage != NULL) {
                $this->processNext(array('transactionId' => $transactionId, 'queueMessage' => $this->processQueueFormModel->processQueueMessage));
            } else {
                $this->processNext(array('transactionId' => $transactionId));
            }
        }

        if ($this->isAjaxLinkClicked('stopProcessQueueLink')) {
            $this->stopProcessQueue(array('transactionId' => $transactionId));
        }

        $allProcessedQueues = BMServiceQueueLineTransactionQueue::model()->findAllByAttributes(
                array('transaction_id' => $transactionId, 'processqueue_status' => BAQQueueLine::processQueueStatus_Processed));

        $processedQueueCount = count($allProcessedQueues);

        $processQueueStatus['processedQueue'] = $processedQueueCount;

        foreach ($allProcessedQueues as $processedQueue) {
            $data = unserialize($processedQueue->data);
            $startTime = $data[BAQQueueLine::processQueueStatus_StartProcessTime];
            $endTime = $data[BAQQueueLine::processQueueStatus_EndProcessTime];
            $totalProcessTime += $endTime - $startTime;
            $count++;
        }

        if ($count != 0) {
            $averageProcessTime = intval($totalProcessTime / $count);
            $processQueueStatus['averageProcessTime'] = $averageProcessTime;
        }

        if ($userId == NULL)
            $userId = Blyn::app()->getCurrentUser()->getId();

        //find current process queue
        $mCurrentTranQueue = BMServiceQueueLineTransactionQueue::model()->findByAttributes(array('transaction_id' => $transactionId,
            'processqueue_status' => BAQQueueLine::processQueueStatus_Processing));

        if ($mCurrentTranQueue != NULL) {
            $processQueueStatus['processingQueue'] = $mCurrentTranQueue->queue_number;
            $currentProcessingQueue = $processQueueStatus['processingQueue'];

            //get message of queue
            $messages = array();
            $mQueueMessages = BMAOnlineQueueMessage::model()->findAllBySql(
                    'select * from bln_app_onlinequeue_message where  queue_number = :QueueNumber and queue_transaction_id = :TransactionId order by send_time desc  ', array(':QueueNumber' => $currentProcessingQueue, 'TransactionId' => $transactionId));

            foreach ($mQueueMessages as $mMessage) {
                $message = array();
                $message['id'] = $mMessage->_id;
                $message['transactionId'] = $mMessage->queue_transaction_id;
                $message['queueNumber'] = $mMessage->queue_number;
                $message['senderId'] = $mMessage->sender_id;
                $message['sendTime'] = $mMessage->send_time;
                $message['message'] = $mMessage->data;
                //$message['sender'] = new BUser($mMessage['sender_id']);

                $messages[$mMessage->_id] = $message;
            }
            $processQueueStatus['queueMessages'] = $messages;
        }

        //find next process queue
        $mTranQueue = BMServiceQueueLineTransactionQueue::model()->findBySql(
                'select * from bln_app_onlinequeue_service_queueline_transaction_queue where
                    transaction_id = :TransactionId and processqueue_status = :ProcessStatus and queue_number > :CurrentQueueCount', array(':TransactionId' => $transactionId, ':CurrentQueueCount' => $currentProcessingQueue,
            ':ProcessStatus' => BAQQueueLine::processQueueStatus_Pending));

        if ($mTranQueue != NULL) {
            $processQueueStatus['nextQueue'] = $mTranQueue->queue_number;
        }

        $allPendingQueues = BMServiceQueueLineTransactionQueue::model()->findAllByAttributes(
                array('transaction_id' => $transactionId, 'processqueue_status' => BAQQueueLine::processQueueStatus_Pending));

        $pendingCount = count($allPendingQueues);

        $processQueueStatus['pendingQueue'] = $pendingCount;

        //get waiting time in minutes     
        $waitingTime = -1;
        $estimateTime = '';
        if ($averageProcessTime > 0 && $pendingCount > 0) {
            $waitingTime = $averageProcessTime * $pendingCount;

            $waitingSeconds = $waitingTime % 60;
            $waitingMins = (($waitingTime - $waitingSeconds) % (60 * 60)) / 60;
            $waitingHours = ($waitingTime - $waitingSeconds - $waitingMins * 60) / (60 * 60);

            if ($waitingHours > 1)
                $estimateTime = $waitingHours . ' hours';
            if ($waitingMins > 1)
                $estimateTime .= $waitingMins . ' minutes';
            if ($waitingSeconds > 1)
                $estimateTime .= $waitingSeconds . ' seconds';
            $processQueueStatus['estimateWaitingTime'] = $estimateTime;
        }

        return $processQueueStatus;
    }

    public function populateProcessQueueLink($processQueueStatus = NULL) {
        $link = $this->buildLink('processQueueLink', "Process Queue", BUIScreen::LinkType_AjaxButton);
    }

    public function populateQueueLineLinks($ajaxPlace = null) {
        $qlineLinks = array();
        $qLines = Blyn::app()->getActiveServiceApp()->getQueueLines();
        if ($qLines == NULL)
            return array();

        //      $isLinkClicked = FALSE;
        $activeId = $this->getTransitVariable('activeQueueLineId');
        $activeId = isset($_REQUEST['queueLineId']) ? $_REQUEST['queueLineId'] : $activeId;
        if ($activeId == NULL) {
            reset($qLines);
            foreach ($qLines as $qLine) {
                $transactions = $qLine->getTransactions(array('processQueueTime' => time()));
                if (count($transactions) > 0) {
                    $activeId = $qLine->id;
                    break;
                }
            }
        }

        $this->addTransitVariable('activeQueueLineId', $activeId);

        foreach ($qLines as $qLine) {
            $qLineLink = array();
            $qLineLink['id'] = $qLine->id;
            $qLineLink['active'] = FALSE;
            //first set active link
            if ($activeId == $qLine->id)
                $qLineLink['active'] = TRUE;
            $link = $this->buildLink('queueLine' . $qLine->id, $qLine->name, BUIScreen::LinkType_AjaxLink, NULL, array('queueLineId' => $qLine->id));
            $qLineLink['ajaxLink'] = $link;
            $qlineLinks[$qLine->id] = $qLineLink;
        }

        return $qlineLinks;
    }

    public function getActiveQueueLine() {
        $qLindId = $this->getTransitVariable('activeQueueLineId');
        return BAQQueueLine::find(array(BAQQueueLine::key_QueueLineId => $qLindId));
    }

}

?>
